package hot100;

import java.util.LinkedList;
import java.util.List;

public class Solution39 {

    List<List<Integer>> ans = new LinkedList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<Integer> list = new LinkedList<>();
        dfs(target, candidates, 0, list);
        return ans;
    }

    public void dfs(int target, int[] candidates, int index, List<Integer> list) {
        if (target <= 0 || index >= candidates.length) {
            if (target == 0) {
                ans.add(new LinkedList<>(list));
            }
            return;
        }
        dfs(target, candidates, index + 1, list);
        if (target - candidates[index] >= 0) {
            list.add(candidates[index]);
            dfs(target - candidates[index], candidates, index, list);
            list.remove(list.size() - 1);
        }
    }
}
